﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Configuration;
using EasyCode.Utility;
using System.IO;

public partial class ACP_AdminUploadMCE : System.Web.UI.Page
{
    private string type = string.Empty;
    private int statIndex = 0;
    private int amount = 10;
    private int curPage = 1;
    private int Stt = 0;
    private string filePath = string.Empty;
    private string MoviePath = string.Empty;
    private string ImgPathUrl = string.Empty;
    private string Tip = string.Empty;

    private string[] arrImg = { ".JPG", ".JPEG", ".PNG", ".GIF" };
    private string[] arrVideo = { ".SWF", ".AVI", ".FLV" };


    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        if (Session["UserName"] == null)
        {
            string currentURL = Request.Url.PathAndQuery;
            Response.Redirect("Login.aspx?returnURL=" + HttpUtility.UrlEncode(currentURL));
        }
        else
        {
            string currentPage = Path.GetFileName(Request.PhysicalPath);
            if (currentPage.ToLower() != "default.aspx")
            {
                GlobalVariable.CurrentPage = currentPage;
                if (!CheckRoles.CanView())
                {
                    Response.Redirect(ResolveUrl("~/Page/AccessDeny.aspx"));
                }
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!CheckRoles.CanEdit())
        {
            Response.Redirect(ResolveUrl("~/Page/AccessDeny.aspx"));
        }
        if (!CheckRoles.CanInsert())
        {
            Response.Redirect(ResolveUrl("~/Page/AccessDeny.aspx"));
        }
        if (!CheckRoles.CanDelete())
        {
            Response.Redirect(ResolveUrl("~/Page/AccessDeny.aspx"));
        }

        if (Session["ImagePath"] != null)
        {
            this.ImgPathUrl = Session["ImagePath"].ToString();
        }
        if (Session["MoviePath"] != null)
        {
            this.MoviePath = Session["MoviePath"].ToString();
        }
        if (!this.Page.IsPostBack)
        {
            this.BindData();
        }
    }

    protected void BindData()
    {
        this.type = Protector.String(this.Request.QueryString["type"], "img");

        if (this.type.ToUpper() == "IMG" && this.ImgPathUrl != string.Empty)
        {
            this.filePath = this.ImgPathUrl;
        }
        else if (this.type.ToUpper() == "VIDEO" && this.MoviePath != string.Empty)
        {
            this.filePath = this.MoviePath;
        }

        if (this.filePath != string.Empty)
        {
            string fileFolder = Server.MapPath(this.filePath);
            string[] files = Directory.GetFiles(fileFolder);

            if (files != null && files.Length > 0)
            {
                if (this.type.ToUpper() == "IMG")
                {
                    files = (from dt in files
                             join dts in this.arrImg on (Path.GetExtension(dt).ToUpper()) equals dts
                             orderby Directory.GetLastWriteTime(dt) descending
                             select dt).ToArray();
                }
                else if (this.type.ToUpper() == "VIDEO")
                {
                    files = (from dt in files
                             join dts in this.arrVideo on (Path.GetExtension(dt).ToUpper()) equals dts
                             orderby Directory.GetLastWriteTime(dt) descending
                             select dt).ToArray();
                }

                this.LiteralNoRecord.Visible = false;
                this.divRecord.Visible = true;

                Dictionary<int, string> myDic = new Dictionary<int, string>();
                int index = 0;

                foreach (string file in files)
                {
                    string originalPath = Path.GetFileName(file);
                    myDic.Add(index, this.filePath + originalPath);
                    index++;
                }

                this.curPage = Protector.Int(this.Request.QueryString["Page"], 1);
                this.statIndex = (this.curPage - 1) * amount;
                this.Stt = this.statIndex + 1;

                myDic = (from dt in myDic
                         select dt).Skip(this.statIndex).Take(this.amount).ToDictionary(dt => dt.Key, dt => dt.Value);

                this.RepeaterPhoto.DataSource = myDic;
                this.RepeaterPhoto.DataBind();

                if (this.Request.QueryString["type"] != null)
                {
                    this.LiteralPaging.Text = Commons.LinkPagingTypeIframe(this.GetUrl(this.Request.Url.PathAndQuery), index, this.amount, this.curPage, 2, "left");
                }
                else
                {
                    this.LiteralPaging.Text = Commons.LinkPagingTypeIframe(this.GetUrl(this.Request.Url.PathAndQuery), index, this.amount, this.curPage, 1, "left");
                }
            }
            else
            {
                this.LiteralNoRecord.Visible = true;
                this.divRecord.Visible = false;
            }
        }
        else
        {
            this.LiteralNoRecord.Visible = true;
            this.divRecord.Visible = false;
        }
    }

    protected int GetStt()
    {
        return this.Stt++;
    }

    protected void RepeaterPhoto_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "Delete" && e.CommandArgument != string.Empty)
        {
            this.type = Protector.String(this.Request.QueryString["type"], "img");
            if (this.type.ToUpper() == "IMG" && this.ImgPathUrl != string.Empty)
            {
                this.filePath = this.ImgPathUrl;
            }
            else if (this.type.ToUpper() == "VIDEO" && this.MoviePath != string.Empty)
            {
                this.filePath = this.MoviePath;
            }

            if (this.filePath != string.Empty)
            {

                FileInfo myFile = new FileInfo(Server.MapPath(this.filePath) + e.CommandArgument);

                if (myFile.Exists)
                {
                    myFile.Delete();

                    this.curPage = Protector.Int(this.Request.QueryString["Page"], 1);

                    if (this.curPage != 1 && this.RepeaterPhoto.Items.Count == 1)
                    {
                        this.Response.Redirect(this.Request.Url.PathAndQuery.Replace("Page=" + this.curPage, "Page=" + (this.curPage - 1).ToString()));
                    }
                    else
                    {
                        this.BindData();
                    }
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "active", "ClickClose();", true);
                }
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "active", "ClickClose();", true);
            }
        }
    }

    protected void RepeaterPhoto_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e != null && e.Item != null)
        {
            KeyValuePair<int, string> itemData = (KeyValuePair<int, string>)e.Item.DataItem;
            HyperLink HyperLinkFileName = (HyperLink)e.Item.FindControl("HyperLinkFileName");
            string FilePath = string.Empty;
            string ect = string.Empty;

            if (itemData.Value != null)
            {
                FilePath = itemData.Value;

                ect = Path.GetExtension(FilePath).ToUpper();
                FilePath = FilePath.Replace("~/", "../");
                if (ect == ".AVI")
                {
                    HyperLinkFileName.Attributes.Add("onclick", "parent.ReceivedDataAVI('" + FilePath + "');");
                }
                else if (ect == ".FLV")
                {
                    HyperLinkFileName.Attributes.Add("onclick", "parent.ReceivedDataFLV('" + FilePath + "');");
                }
                else if (ect == ".SWF")
                {
                    HyperLinkFileName.Attributes.Add("onclick", "parent.ReceivedDataSWF('" + FilePath + "');");
                }
                else
                {

                    HyperLinkFileName.Attributes.Add("onclick", "parent.ReceivedDataIMG('" + FilePath + "');");

                    this.Tip = "<img style=\"max-height: 200px; max-width: 200px;\" src=\"" + FilePath + "\" />";
                    HyperLinkFileName.Attributes.Add("onmouseover", "Tip('" + this.GetTip() + "');");
                    HyperLinkFileName.Attributes.Add("onmouseout", "UnTip();");
                }
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "active", "ClickClose();", true);
            }
        }
        else
        {
            ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "active", "ClickClose();", true);
        }
    }

    protected string GetTip()
    {
        return this.Tip;
    }

    protected string GetUrl(string curUrl)
    {
        if (Request.QueryString["Page"] != null)
        {
            int _page = Protector.Int(Request.QueryString["Page"]);
            if (curUrl.Contains("&Page"))
            {
                curUrl = curUrl.Replace(("&Page=" + _page.ToString()), "");
            }
            else if (curUrl.Contains("?Page"))
            {
                curUrl = curUrl.Replace(("?Page=" + _page.ToString()), "");
            }
        }
        return curUrl;
    }

    protected void ButtonUpload_Click(object sender, EventArgs e)
    {
        if (this.IsValid)
        {
            if (!this.FileUpload.HasFile)
            {
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "active", "ChooseLogo();", true);
                return;
            }
            this.type = Protector.String(this.Request.QueryString["type"], "img");
            if (this.type.ToUpper() == "IMG" && this.ImgPathUrl != string.Empty)
            {
                this.filePath = this.ImgPathUrl;
            }
            else if (this.type.ToUpper() == "VIDEO" && this.MoviePath != string.Empty)
            {
                this.filePath = this.MoviePath;
            }
            string extension = System.IO.Path.GetExtension(FileUpload.PostedFile.FileName).ToUpper();
            if (extension == null || (type.ToUpper() == "IMG" && !Commons.CheckImageType(extension)) || (type.ToUpper() == "VIDEO" && !Commons.CheckMovieType(extension)))
            {
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "active", "ErrorFileUpload();", true);
                return;
            }
            string fileName = Guid.NewGuid().ToString() + extension;
            string sourcePath = Server.MapPath(this.ResolveUrl(this.filePath) + fileName);
            this.FileUpload.SaveAs(sourcePath);
            this.BindData();
        }
        else
        {
            this.Page.ClientScript.RegisterStartupScript(this.GetType(), "active", "ClickClose();", true);
        }
    }
}